<template>
  <ElDialog
    :model-value="visible"
    :title="title"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      @keyup.enter="handleSubmit"
    >
      <ElRow :gutter="20">
        <ElCol :span="24" v-if="parentData">
          <ElFormItem label="上级分类">
            <ElInput
              :value="parentData.categoryName"
              disabled
              placeholder="顶级分类"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="分类名称" prop="categoryName">
            <ElInput
              v-model="formData.categoryName"
              placeholder="请输入分类名称"
              maxlength="50"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="分类编码" prop="categoryCode">
            <ElInput
              v-model="formData.categoryCode"
              placeholder="请输入分类编码"
              maxlength="30"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="排序号" prop="orderNum">
            <ElInputNumber
              v-model="formData.orderNum"
              :min="0"
              :max="999"
              placeholder="排序号"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>

        <ElCol :span="12">
          <ElFormItem label="状态" prop="status">
            <ElRadioGroup v-model="formData.status">
              <ElRadio :value="1">正常</ElRadio>
              <ElRadio :value="0">停用</ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="200"
              show-word-limit
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <ElButton @click="handleClose">取消</ElButton>
      <ElButton type="primary" :loading="submitting" @click="handleSubmit">
        确定
      </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({ name: "WmsItemCategoryDialog" });

// Props
interface Props {
  visible: boolean;
  type: "add" | "edit";
  categoryData?: WMS.Basic.ItemCategoryInfo | null;
  parentData?: WMS.Basic.ItemCategoryInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  categoryData: null,
  parentData: null,
});

// Emits
const emit = defineEmits<{
  "update:visible": [visible: boolean];
  submit: [data: WMS.Basic.ItemCategoryInfo];
}>();

// Form ref
const formRef = ref<FormInstance>();

// 提交状态
const submitting = ref(false);

// 弹窗标题
const title = computed(() => {
  if (props.type === "edit") {
    return "编辑分类";
  }
  return props.parentData ? "新增子分类" : "新增分类";
});

// 表单数据
const formData = reactive<Partial<WMS.Basic.ItemCategoryInfo>>({
  categoryName: "",
  categoryCode: "",
  parentId: 0,
  orderNum: 0,
  status: 1,
  remark: "",
});

// 表单验证规则
const rules: FormRules = {
  categoryName: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  categoryCode: [
    { required: true, message: "请输入分类编码", trigger: "blur" },
    { min: 2, max: 30, message: "长度在 2 到 30 个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_-]+$/,
      message: "只能包含字母、数字、下划线和中划线",
      trigger: "blur",
    },
  ],
  orderNum: [
    { required: true, message: "请输入排序号", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 999,
      message: "排序号范围为 0-999",
      trigger: "blur",
    },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 监听数据变化，初始化表单
watch(
  () => [props.visible, props.categoryData, props.parentData],
  () => {
    if (props.visible) {
      resetForm();
      if (props.type === "edit" && props.categoryData) {
        Object.assign(formData, {
          id: props.categoryData.id,
          categoryName: props.categoryData.categoryName,
          categoryCode: props.categoryData.categoryCode,
          parentId: props.categoryData.parentId || 0,
          orderNum: props.categoryData.orderNum || 0,
          status: props.categoryData.status,
          remark: props.categoryData.remark || "",
        });
      } else if (props.parentData) {
        // 新增子分类
        formData.parentId = props.parentData.id;
      }
    }
  },
  { immediate: true },
);

// 重置表单
const resetForm = () => {
  formData.categoryName = "";
  formData.categoryCode = "";
  formData.parentId = 0;
  formData.orderNum = 0;
  formData.status = 1;
  formData.remark = "";
  formRef.value?.clearValidate();
};

// 关闭弹窗
const handleClose = () => {
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const submitData = {
      ...formData,
      parentId: formData.parentId || 0,
    } as WMS.Basic.ItemCategoryInfo;

    emit("submit", submitData);
  } catch (error) {
    console.error("Form validation failed:", error);
  } finally {
    submitting.value = false;
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
